<?php

namespace app\admin\utils\model;

use plugin\admin\app\model\Base;

/**
 * @property integer $id 主键(主键)
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property string $code 语言代码
 * @property string $name 语种
 */
class UtilLang extends Base
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'util_lang';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';
    

    // 判断是否存在某个语言包
    static function isHas($text){
        if(!UtilLangDetail::where(['lang_id'=>0,'text'=>$text])->exists()){
            $date = date('Y-m-d H:i:s');
            return UtilLangDetail::insertGetId([
                'created_at'=>$date,
                'updated_at'=>$date,
                'lang_id'=>0,
                'tid'=>0,
                'text'=>$text,
            ]);
        }
        return true;
    }

    static function generate(){
        $list = UtilLang::whereRaw('1')->get();
        $path = base_path().'/resource/translations/';
        $langList = UtilLangDetail::where(['lang_id'=>0])->get();
        foreach ($list as $item){
            $langArr = [];
            foreach ($langList as $v){
                $yiwen = UtilLangDetail::where(['lang_id'=>$item->id,'tid'=>$v->id])->value('text');
                if($yiwen){
                    $langArr[$v->text] = $yiwen;
                }
            }
            if(count($langArr)>0){
                if(!file_exists($path.$item->code)){
                    mkdirs($path.$item->code);
                }
                self::saveFile($path.$item->code.'/messages.php',$langArr);
            }
        }
    }

    // 保存数据到文件
    protected static function saveFile($file,$data){
        $text = "<?php \r\n return ".var_export($data,true).';';
        file_put_contents($file,$text);
    }
}
